﻿using Company.Core.Helpers;
using System.IO.Ports;
using System.Text;

namespace Company.Hardware.Base.Helpers
{
    /// <summary>
    /// 串口服务类
    /// </summary>
    public class SerialPortService
    {
        private SerialPort? serialPort;
        public bool Connected { get; set; } = false;
        public bool IsStarted { get; set; } = false;

        public event Action<string>? OnReceived;

        public bool ConnectionAsync(Config config)
        {
            try
            {
                if (string.IsNullOrEmpty(config.SerialName))
                {
                    Logs.Error($"{this.GetType().FullName}SerialName不能为空");
                    return false;
                }
                serialPort = new SerialPort(config.SerialName,config.BaudRate);
                serialPort.DataReceived += SerialPort_DataReceived;
                serialPort.Open();
                Connected = serialPort.IsOpen;
                IsStarted= serialPort.IsOpen;
            }
            catch(Exception ex)
            {
                Logs.Error(ex);
                return false;
            }

            return true;
        }


        private void SerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            int length = serialPort.BytesToRead;
            byte[] buffer = new byte[length];
            serialPort.Read(buffer, 0, length);
            string content = Encoding.Default.GetString(buffer);
            OnReceived?.Invoke(content);
        }
    }
}
